package com.douya.mvc.handler;

import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.douya.common.enums.CommonResultEnums;
import com.douya.common.pojo.vo.CommonResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * sentinel异常处理
 *
 * @Author hcy
 * @Date 2023/2/27
 */
@ControllerAdvice
@Order(0)
@Slf4j
public class SentinelBlockExceptionHandler {

    @ExceptionHandler(BlockException.class)
    @ResponseBody
    public CommonResponseVO<?> sentinelBlockHandler(BlockException e) {
        AbstractRule rule = e.getRule();
        String requestURI = rule.getResource();
        // 暂时统一返回
        return CommonResponseVO.error(
                CommonResultEnums.FORBIDDEN,
                requestURI + " api limit"
        );
//        // 不同的异常返回不同的提示语
//        if (e instanceof FlowException) {
//            errorResponse.setMessage(requestURI + "被限流了");
//        } else if (e instanceof DegradeException) {
//            errorResponse.setMessage(requestURI + "服务降级了");
//        } else if (e instanceof ParamFlowException) {
//            errorResponse.setMessage(requestURI + "被热点限流了");
//        } else if (e instanceof SystemBlockException) {
//            errorResponse.setMessage(requestURI + "被系统保护了");
//            errorResponse.setCode(4);
//        } else if (e instanceof AuthorityException) {
//            errorResponse.setMessage(requestURI + "被授权了");
//        }
    }
}
